package com.eims.ball.info.fragment;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringXmlRequest;

import com.contans.view.FenxizhengrongVo;

import com.eims.sls_app.view.MyToast;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import bls.juejin.cn.R;
import progressBar.ProgressDialogBar;

public class FenxiZhengrongFragment extends Fragment implements OnClickListener {
    private Activity activity;
    private TextView tvMainTeam, tvGuesTeam;
    public int tvId;

    private String infoId, hid, gid, mainName, GuesName;

    private MyHandler handler;

    FenxizhengrongVo fenxizhengrongVo;

    public FenxiZhengrongFragment() {
        super();
    }

    public static FenxiZhengrongFragment newInstance(String infoId, String hid, String gid, String mainName, String GuesName) {

        Bundle args = new Bundle();

        FenxiZhengrongFragment fragment = new FenxiZhengrongFragment();
        args.putString("infoId",infoId);
        args.putString("hid",hid);
        args.putString("gid",gid);
        args.putString("mainName",mainName);
        args.putString("GuesName",GuesName);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.zhenrong_fragment, container, false);
        activity = getActivity();

        Bundle args = getArguments();
        if (args != null) {
            this.infoId = args.getString("infoId");
            this.hid= args.getString("hid");
            this.gid = args.getString("gid");
            this.mainName= args.getString("mainName");
            this.GuesName= args.getString("GuesName");

        }
        handler = new MyHandler();
        init(view);

        getBalllInfo(infoId);
        return view;
    }

    private void init(View view) {
        // TODO Auto-generated method stub
        tvMainTeam = (TextView) view.findViewById(R.id.tv_main_team);
        tvGuesTeam = (TextView) view.findViewById(R.id.tv_gues_team);
        tvMainTeam.setOnClickListener(this);
        tvGuesTeam.setOnClickListener(this);

    }

    public void changeFragment(int i) {
        if (i == 1) {
            tvId = R.id.tv_main_team;

            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, FenxiHenrongMaintemFragment.newInstance(fenxizhengrongVo.getWeakPlayerA(), fenxizhengrongVo.getAllPlayerA()), "main");

            transaction.commitAllowingStateLoss();

        } else {

            tvId = R.id.tv_gues_team;

            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, FenxiHenrongGuestemFragment.newInstance(fenxizhengrongVo.getWeakPlayerB(), fenxizhengrongVo.getAllPlayerB()), "gues");

            transaction.commitAllowingStateLoss();

        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_main_team:
                if (tvId != R.id.tv_main_team) {
                    tvMainTeam.setBackgroundResource(R.color.main_write);
                    tvGuesTeam.setBackgroundResource(R.color.main_huise);
                    changeFragment(1);
                }
                break;
            case R.id.tv_gues_team:
                if (tvId != R.id.tv_gues_team) {
                    tvMainTeam.setBackgroundResource(R.color.main_huise);
                    tvGuesTeam.setBackgroundResource(R.color.main_write);
                    changeFragment(2);
                }
                break;

            default:
                break;
        }
    }

    public void getBalllInfo(String id) {
        MySingleton mySingleton = MySingleton.getInstance(activity);
        ProgressDialogBar.startProgress(activity, "", true);
        StringXmlRequest jsonObjectRequest = new StringXmlRequest(Request.Method.GET,
                "http://01link.igowu123.com/qtjsbf/jc/newroundplayerdata/" + id + ".xml", new Response.Listener<String>() {
            @Override
            public void onResponse(String tn) {

                // Log.i("RealTime", "request--------success------" + tn);

                try {
                    JSONObject item = XML.toJSONObject(tn);

                    Log.e("JSON", item.toString());

                    String resultRep = item.optString("rows");

                    item = new JSONObject(resultRep);

                    String CreditinfoStr = item.getString("row");

                    if (CreditinfoStr != null && !"".equals(CreditinfoStr)) {
                        JSONObject array2 = new JSONObject(CreditinfoStr);

                        fenxizhengrongVo = new FenxizhengrongVo();

                        fenxizhengrongVo.setTeamNameA(array2.optString("teamNameA"));
                        fenxizhengrongVo.setTeamNameB(array2.optString("teamNameB"));
                        fenxizhengrongVo.setZxPlayerA(array2.optString("ZxPlayerA"));
                        fenxizhengrongVo.setZxPlayerB(array2.optString("ZxPlayerB"));
                        fenxizhengrongVo.setWeakPlayerA(array2.optString("weakPlayerA"));
                        fenxizhengrongVo.setWeakPlayerB(array2.optString("weakPlayerB"));
                        fenxizhengrongVo.setAllPlayerA(array2.optString("allPlayerA"));
                        fenxizhengrongVo.setAllPlayerB(array2.optString("allPlayerB"));

                    }


                    handler.sendEmptyMessage(1);

                    //
                } catch (JSONException e) {
                    Log.e("JSON", "xml->json失败" + e.getLocalizedMessage());
//							MyToast.getToast(activity, "获取失败").show();

                }
                ProgressDialogBar.stopProgress();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("RealTime", "request--------success------" + error);
                MyToast.getToast(activity, "获取失败").show();
                ProgressDialogBar.stopProgress();
            }

        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> params = new HashMap<String, String>();
                // params.put("appid", "0af5281058488ec1784e433f69d45d81");
                // params.put("custNo", "gl00014156");
                // params.put("orderId", attach);

                return params;
            }
        };

        jsonObjectRequest.setShouldCache(false);// 是否设置缓存

        mySingleton.addToRequestQueue(jsonObjectRequest);

    }

    @SuppressLint("HandlerLeak")
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    changeFragment(1);
                    break;
                case 1:
                    tvMainTeam.setText(fenxizhengrongVo.getTeamNameA());
                    tvGuesTeam.setText(fenxizhengrongVo.getTeamNameB());
                    changeFragment(1);

                    break;
                default:
                    Toast.makeText(getActivity(), "网络异常，加载失败。", Toast.LENGTH_SHORT).show();
                    break;
            }
            super.handleMessage(msg);
        }
    }

}
